/**** JQUERY MEDIA PLAYER ****/

(function ($) {

    var ytPlayer, soundcloud, bandcamp, vimeo, debug = true, $wrapper;

    $.MediaPlayer = function (params) {

        var currentTrack = {
            name: 'Chip World- ChipTune',
            url: 'http://soundcloud.com/beschizza/chip-world',
            id: 'chip-world',
            time: '03:22',
            pos: '01:27'
        };
        //player is the public object that is returned
        var player = {
            ctrls: {
                Play: function () {
                    $(player).trigger('OnPlay', currentTrack);
                    if (debug)
                        console.log('$.MediaPlayer.Play()')
                },
                Stop: function () {
                    $(player).trigger('OnStop', currentTrack);
                    if (debug)
                        console.log('$.MediaPlayer.Stop()')
                },
                Pause: function () {
                    $(player).trigger('OnPause', currentTrack);
                    if (debug)
                        console.log('$.MediaPlayer.Pause()')
                },
                Prev: function () {
                    $(player).trigger('OnPrev', currentTrack);
                    if (debug)
                        console.log('$.MediaPlayer.Prev()')
                },
                Next: function () {
                    $(player).trigger('OnNext', currentTrack);
                    if (debug)
                        console.log('$.MediaPlayer.Next()')
                }
            },
            //Objects
            Playlist: [], //list of tracks {name,url,id,time,pos}
            //Functions
            AddTrack: function (url) {
                var track = GetTrackFromUrl(url);
                this.Playlist.push(track);
            }

        };

        //bind events to object
        //		$(player).bind('OnPlay');
        //		$(player).bind('OnStop');
        //		$(player).bind('OnPause');
        //		$(player).bind('OnPrev');
        //		$(player).bind('OnNext');

        //add jquery Selector
        player.$ = $(player);
        $(this).bind('Loaded', function () {
            alert('loaded!'):
            return player;
        });
    };
    /**** INIT ****/
    (function () {
        //Load all of our dependant scripts
        LoadDependantScripts(function () {

            //check if we have a wrapper otherwis create one and append it to the dom
            $(document).ready(function () {
                if (!$wrapper) {
                    $wrapper = $('<div class="MediaPlayerWrapper" style="display:block;">MediaPlayer</div>').appendTo('body');
                }
                ytPlayer = $('<div class="ytPlayer2" id="ytPlayer2" />').appendTo($wrapper);
                ytPlayer.YouTubePlayer();
                $(this).trigger('Loaded');
            });
        });
    })();


    //jQuery selector init
    $.fn.MediaPlayer = function () {
        $wrapper = $(this);
        return $.MediaPlayer();
    };

    /**** PRIVATE FUNCTIONS ****/

    /*
    * Gets a track object from the givven url, can check vimeo, bandcamp and youtube
    * uses internal functions to get info
    */
    function GetTrackFromUrl(url) {

        if (!url)
            return;
        var track;
        if (url.contains('youtube'))
            track = GetYoutubeTrackFromUrl(url);
        else if (url.contains('bandcamp'))
            track = GetBandcampTrackFromUrl(url);
        else if (url.contains('soundcloud'))
            track = GetSoundcloudTrackFromUrl(url);

        return track;
    }

    /*
    * Gets a track from youtube
    *
    */
    function GetYoutubeTrackFromUrl(url) {
        //while(!ytPlayer){console.log('waiting for ytPlayer....')};
        var videoId = ytPlayer.GetYoutubeIdFromUrl(url);
        var url = 'http://gdata.youtube.com/feeds/api/videos/' + videoId + '?v=2&alt=jsonc';
        $.getJSON(url, function (res) {
            var track = res.data;
        });
    }


    /*
    * Loads the default script needed for the media player
    * Should be able to be extended with user scripts
    */
    function LoadDependantScripts(callback) {
        var scripts = [
			'core/jquery.mp3player.js',
			'core/jQuery.YouTubePlayer.js',
			'services/soundcloud.js',
			'services/bandcamp.js'
		];
        var finished = scripts.length - 1;
        var count = 0;
        $(scripts).each(function () {
            if (debug)
                console.log('Loading script: ' + this);
            $.getScript(this, function () {
                count++;
                if (count == finished)
                    callback();
            });
        });
    }
    /**** javascript extensions ****/
    String.prototype.contains = function (it) { return this.indexOf(it) !== -1; };

})(jQuery);